package com.hujia.service;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;

import com.hujia.entity.City;
import com.hujia.entity.Province;
import com.hujia.rs.redis.RedisProvider;

import io.vertx.core.Future;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.redis.RedisClient;

public class ProvinceService {

	/**
	 * 加载省份数据到redis中
	 */
	public Future<Void> loadProvinceData() {

		Future<Void> future = Future.future();
		InputStream is = null;
		try {
			is = Province.class.getClassLoader().getResourceAsStream("provinces.json");
			String provinceData = IOUtils.toString(is, StandardCharsets.UTF_8);
			JsonArray provinces = new JsonArray(provinceData);
			if (provinces == null || provinces.isEmpty()) {
				future.fail("省份数据读取失败");
			}

			// 存一个region的key
			// 存一个省份的有序集合
			JsonObject regions = new JsonObject();
			List<String> provinceCode = new ArrayList<String>();
			for (int i = 0; i < provinces.size(); i++) {
				JsonObject jsonObject = provinces.getJsonObject(i);
				String code = jsonObject.getString("code");
				regions.put(String.format("region-%s", code), jsonObject.toString());
				provinceCode.add(code);
			}

			RedisClient redisClient = RedisProvider.getRedisClient();
			redisClient.mset(regions, msetRes -> {
				if (msetRes.succeeded()) {
					redisClient.del("province", res -> {
						if (res.succeeded()) {
							redisClient.saddMany("province", provinceCode, ress -> {
								if (ress.succeeded()) {
									System.out.println("加载省份数据完成.");
									future.complete();
								}
							});
						}
					});
				}
			});
		}catch(Exception ex) {
			future.fail(ex.getMessage());
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}	
		}

		return future;
	}
	
	
	/**
	 * 获取所有的省份
	 */
	public Future<List<Province>> list() {

		Future<List<Province>> future = Future.future();
		RedisClient redisClient = RedisProvider.getRedisClient();
		redisClient.smembers("province", rs -> {

			if (rs.failed()) {
				future.fail(rs.cause().getMessage());
				return;
			}

			JsonArray jsonArray = rs.result();
			if (jsonArray == null || jsonArray.isEmpty()) {
				future.fail("获取省份信息失败.");
				return;
			}

				List<String> keys = new ArrayList<String>();
				for (int i = 0; i < jsonArray.size(); i++) {
					keys.add(String.format("region-%s", jsonArray.getString(i)));
				}

				redisClient.mgetMany(keys, rss -> {
					if (rss.failed()) {
						future.fail(rss.cause().getMessage());
						return;
					}

					JsonArray provinceJsonArray = rss.result();
					if (provinceJsonArray == null || provinceJsonArray.isEmpty()) { 
						future.fail("获取省份信息失败.");
						return;
					}
					
					List<Province> provinces = new ArrayList<Province>();
					for (int i = 0; i < provinceJsonArray.size(); i++) {
						Province province = new Province();
						try {
							 JsonObject jsonObject = new JsonObject(provinceJsonArray.getString(i));
							province.sacn(jsonObject);
						} catch (Exception e) {
							e.printStackTrace();
							future.fail(e.getMessage());
							return;
						}
						provinces.add(province);
					}
					future.complete(provinces);
				});
		});

		return future;
	}
	
	/**
	 * 获取城市的子节点
	 */
	public Future<List<City>> children(String provinceCode) {
		Future<List<City>> future = Future.future();
		
		RedisClient redisClient = RedisProvider.getRedisClient();
		String key = String.format("province-%s", provinceCode);
		
		redisClient.smembers(key, rs-> {
			
			if (rs.failed()) {
				future.fail(rs.cause().getMessage());
				return;
			}
			
			JsonArray jsonArray = rs.result();
			List<String> keys = new ArrayList<String>();
			for (int i=0;i< jsonArray.size() ;i++) {
				keys.add(String.format("region-%s", jsonArray.getString(i)));
			}
			
			redisClient.mgetMany(keys, rss-> {
				if (rss.failed()) {
					future.fail(rs.cause().getMessage());
					return;
				}
				
				JsonArray cityJsonArray = rss.result();
				if (cityJsonArray == null || cityJsonArray.isEmpty()) {
					future.fail("获取失败.");
					return;
				}
				
				List<City> citys = new ArrayList<City>();
				for (int i = 0; i < cityJsonArray.size(); i++) {
					City city = new City();
					try {
						 JsonObject jsonObject = new JsonObject(cityJsonArray.getString(i));
						 city.scan(jsonObject);
					} catch (Exception e) {
						e.printStackTrace();
						future.fail(e.getMessage());
						return;
					}
					citys.add(city);
				}
				future.complete(citys);
			});
		});
		
		return future;
	}
	

}
